<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="houseData" class="form-container" :rules="houseRules">
      <div class="createPost-main-container">
        <!-- 标题 -->
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="houseData.title" :maxlength="100" name="name" required>
                标题
              </MDinput>
            </el-form-item>
            <!-- 配置 -->
            <div class="postInfo-container">
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="60px" label="面积:" class="postInfo-container-item" prop="area">
                    <el-input v-model="houseData.area"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label-width="120px" label="价格(每平/元):" class="postInfo-container-item" prop="price">
                    <el-input v-model="houseData.price"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="60px" label="地区:" class="postInfo-container-item">
                    <el-select v-model="houseData.zoneId" placeholder="请选择">
                      <el-option v-for="item in zones" :key="item.value" :label="item.label" :value="item.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label-width="120px" label="小区:" class="postInfo-container-item" prop="village">
                    <el-input v-model="houseData.village"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" label="室:" class="postInfo-container-item" prop="room">
                    <el-input v-model="houseData.room"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" label="厅:" class="postInfo-container-item" prop="hall">
                    <el-input v-model="houseData.hall"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" label="卫:" class="postInfo-container-item" prop="bathroom">
                    <el-input v-model="houseData.bathroom"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="介绍:" prop="details">
          <el-input type="textarea" :rows="5" placeholder="请输入内容" class="article-textarea" v-model="houseData.details"
            maxlength="500">
          </el-input>
          <span v-show="detailsLength" class="word-counter">{{detailsLength}}/500</span>
        </el-form-item>

        <el-form-item prop="image_uri" style="margin-bottom: 30px;" label="图片上传">
          <!-- <Upload v-model="" /> -->
          <el-upload class="upload-demo" action="#" :on-success="handleSuccess" :on-change="uploadChange"
            :on-remove="handleRemove" :file-list="fileList" :multiple="true" list-type="picture" :auto-upload="false" ref="upload">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">第一张图片为主图</div>
          </el-upload>
        </el-form-item>
        <el-button type="primary" @click="submitHouse">提交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
  import axios from 'axios'
  import MDinput from '@/components/MDinput'
  import {
    getHouseById,
    removePicture,
    updateHouseById
  } from '@/api/house'
  import { getData } from '@/api/data'
  import store from '@/store'

  export default {
    name: 'houseEdit',
    components: {
      MDinput,
      // Upload,
    },
    props: {},
    data() {
      return {
        houseData: {},
        headers: {
          token: store.getters.token, //headers属性中添加token，这个属性是el-upload自带的用来设置上传请求头部
          houseId: this.$route.params.id
        },
        action: process.env.VUE_APP_BASE_API + "/house/uploadPicture",
        fileList: [],
        imgFile:"",
        zones:[],
        houseRules:{
          title:[{
            required: true,
            trigger: 'blur'
          }],
          area:[{
            required: true,
            trigger: 'blur'
          }],
          village:[{
            required: true,
            trigger: 'blur'
          }],
          room:[{
            required: true,
            trigger: 'blur'
          }],
          hall:[{
            required: true,
            trigger: 'blur'
          }],
          bathroom:[{
            required: true,
            trigger: 'blur'
          }],
          details:[{
            required: true,
            trigger: 'blur'
          }],
          price:[{
            required: true,
            trigger: 'blur'
          }]
        }
      }
    },
    computed: {

    },
    created() {
      const id = this.$route.params && this.$route.params.id
      this.getHouse(id)
      this.getZones()
    },
    methods: {
      async getZones(){
        const {data} = await getData("zone_id")
        for (var i = 0; i < data.length; i++) {
          let obj = {
            value:data[i].valueEn,
            label:data[i].value
          }
          this.zones.push(obj)
        }
      },
      getHouse(id) {
        getHouseById(id).then(res => {
          const {
            data
          } = res
          this.fileList.length = 0
          for (var i = 0; i < data.imgFileNames.length; i++) {
            const obj = {
              name: data.imgFileNames[i],
              url: "https://home-y.oss-cn-hangzhou.aliyuncs.com/" + data.imgFileNames[i]
            }
            this.fileList.push(obj)
          }
          this.imgFile = data.imgFile
          this.houseData = data
          this.houseData.zoneId = String(this.houseData.zoneId)
        })
      },
      submitHouse() {
        updateHouseById(this.houseData).then(res => {
          if (res.code === 1) {
            this.$message({
              message: res.msg,
              type: 'success'
            });
            let formData = new FormData();
            //注意此处是item.raw，如果直接使用files，那么不会有数据传输到后端
            this.fileList.forEach((item) => {
            	formData.append("files", item.raw);
            });
            axios
            	.post("http://localhost:8080/house/uploadPicture", formData, {
            		headers: this.headers
            	})
            	.then(res => {

            	})
            	.catch(error => {
            		this.$message({
            			showClose: true,
            			message: "上传图片失败，请重试",
            			type: 'error'
            		});
            	})
            this.getHouse(this.$route.params.id)
            this.$router.push("/house/list")
          } else {
            this.$message.error(res.msg);
          }
        })
      },
      handleRemove(file, fileList) {
        removePicture(file.name).then(res => {
          if (res.code === 1) {
            this.$message({
              message: res.msg,
              type: 'success'
            })
          } else {
            this.$message.error(res.msg);
          }
        })
      },
      handleSuccess(res, file, fileList) {
        if (res.code === 1) {
          this.$message({
            message: res.msg,
            type: 'success'
          });
          this.getHouse(this.$route.params.id)
        } else {
          this.$message.error(res.msg);
        }
      },
      uploadChange(file, fileList) {
      	let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      	// 判断文件名的类型
      	if (fileType === 'jpg' || fileType === 'png') {
      		let existFile = fileList
      			.slice(0, fileList.length - 1)
      			.find((f) => f.name === file.name);
      		if (existFile) {
      			this.$message.error("当前文件已经存在!");
      			fileList.pop();
      		}
      		this.fileList = fileList;
      	} else {
      		this.$message.error("上传图片只能是png,jpg格式!");
      		fileList.pop();
      		return
      	}
      },
    },
    computed: {
      detailsLength() {
        if (this.houseData.details) {
          return this.houseData.details.length
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }

  .article-textarea ::v-deep {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }
</style>
